package cn.mazexal.exambg.common;

import cn.mazexal.exambg.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

/**
 * @author: Mazexal
 * Date: 2021/9/21
 */
public class UserTokenManager {

    private static final String LOGIN_TOKEN_KEY = "X-EM-Token";

    public static String generateToken(Long id) {
        if (id != null && id > 0) {
            return JwtUtil.createToken(id);
        }
        return "";
    }

    public static Long getUserId(String token) {
        Long userId = JwtUtil.verifyTokenAndGetUserId(token);
        if (userId == null || userId == 0) {
            return -1L;
        }
        return userId;
    }

    public static Long getUserId(HttpServletRequest request) {
        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if (StringUtils.isBlank(token)) {
            return -1L;
        } else {
            return getUserId(token);
        }
    }

}
